﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Text.RegularExpressions;

namespace BoAddonBiz_FreightForwarder.Custom
{
    class CustomsDeclarationXml
    {
        public string CreateXml(string DocEntry, string Type)
        {
            try
            {
                string SQL = string.Empty;
                string CustomsDealaration = string.Empty;
                string TableName = string.Empty;
                XmlDocument CDXml = new XmlDocument();
                SAPbobsCOM.Recordset rs = SAPBoAddon.B1Addon.B1Addon.SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
                CDXml.Load(System.Windows.Forms.Application.StartupPath + @"\Template\CustomsDeclaration.xml");
                TableName = Type == "I" ? "CTC" : "ATC";
                #region 报关单表头信息
                SQL = @"SELECT T8.U_PortCode U_BargainMethodCode,T3.AddId As CargoOwner
                        ,Case When ISNULL(T0.U_TransportCountryC,'') = '' Then (SELECT Code From DPA_empty..CountryOrigin Where Name = T0.U_TransportCountry ) Else T0.U_TransportCountryC End CountryCode
                        ,CASE When ISNULL(T0.U_LoadingPortCode,'') = '' Then (SELECT TOP 1 Code FROM DPA_empty..PortType Where Name = T0.U_LoadingPort) Else T0.U_LoadingPortCode End PortCode
                        ,CASE When '{1}' = 'I' Then T0.U_CollectingRate Else T0.U_SettleMethod End Collecting
                        ,t9.Code FCCurrency
                        ,t10.Code SafeCurrency
                        ,t11.Code OtherCurrency
                        ,T0.*
                    FROM [@AVA_FF_O{2}] T0
						INNER JOIN [@AVA_FF_OBNO] T1 ON T0.U_BaseEntry = T1.DocEntry
                        LEFT JOIN OCRD T3 ON T0.U_CardCode = T3.CardCode
                        LEFT JOIN [@AVA_FF_BAMD] T8 ON T0.U_BargainMethod = T8.Code
                        LEFT JOIN DPA_empty..CurrencyType t9 on t0.U_FCCurrency = t9.Symbol
                        LEFT JOIN DPA_empty..CurrencyType t10 on t0.U_SafeCurrency = t10.Symbol
                        LEFT JOIN DPA_empty..CurrencyType t11 on t0.U_OtherCurrency = t11.Symbol
                    Where T0.DocEntry = {0}";
                SQL = string.Format(SQL, DocEntry, Type, TableName);
                rs.DoQuery(SQL);
                if (rs.RecordCount > 0)
                {
                    CustomsDealaration = rs.Fields.Item("U_CustomsDeclaration").Value.ToString();
                    if (string.IsNullOrEmpty(CustomsDealaration))
                        throw new Exception("预录入编号不能为空。");
                    CDXml.SelectSingleNode("//报关单表头信息/预录入号").InnerText = CustomsDealaration;
                    CDXml.SelectSingleNode("//报关单表头信息/申报单位代码").InnerText = "1105980157";
                    CDXml.SelectSingleNode("//报关单表头信息/申报单位名称").InnerText = "北京海翔国际运输代理有限公司";
                    string DeliverCode = rs.Fields.Item("U_DeliverRegCode").Value.ToString();
                    DeliverCode = DeliverCode == "NO" ? "" : DeliverCode.Substring(0, 5);
                    CDXml.SelectSingleNode("//报关单表头信息/货主单位代码").InnerText = rs.Fields.Item("U_DeliverRegCode").Value.ToString();
                    //CDXml.SelectSingleNode("//报关单表头信息/货主单位名称").InnerText = rs.Fields.Item("U_DeliverName").Value.ToString().Replace("（", "(").Replace("）", ")");
                    CDXml.SelectSingleNode("//报关单表头信息/经营单位编号").InnerText = rs.Fields.Item("U_CusRegCode").Value.ToString();
                    //CDXml.SelectSingleNode("//报关单表头信息/经营单位名称").InnerText = rs.Fields.Item("U_CompanyName").Value.ToString().Replace("（", "(").Replace("）", ")");
                    if (rs.Fields.Item("U_DeliverName").Value != rs.Fields.Item("U_CompanyName").Value)
                    {
                        CDXml.SelectSingleNode("//报关单表头信息/货主单位名称").InnerText = rs.Fields.Item("U_DeliverName").Value.ToString();
                    }
                    CDXml.SelectSingleNode("//报关单表头信息/录入单位代码").InnerText = "1105980157";
                    CDXml.SelectSingleNode("//报关单表头信息/录入单位名称").InnerText = "北京海翔国际运输代理有限公司";
                    CDXml.SelectSingleNode("//报关单表头信息/主管海关或申报地海关").InnerText = rs.Fields.Item("U_ApplyCustoms").Value.ToString();
                    CDXml.SelectSingleNode("//报关单表头信息/进出口岸").InnerText = rs.Fields.Item("U_PortCode").Value.ToString();
                    CDXml.SelectSingleNode("//报关单表头信息/贸易国").InnerText = rs.Fields.Item("CountryCode").Value.ToString();
                    CDXml.SelectSingleNode("//报关单表头信息/贸易港").InnerText = rs.Fields.Item("PortCode").Value.ToString();
                    CDXml.SelectSingleNode("//报关单表头信息/报关转关类型").InnerText = rs.Fields.Item("U_TransferType").Value.ToString();
                    CDXml.SelectSingleNode("//报关单表头信息/报关单类型").InnerText = rs.Fields.Item("U_DocumentType").Value.ToString();
                    CDXml.SelectSingleNode("//报关单表头信息/报关形式类型").InnerText = rs.Fields.Item("U_CustomsStyleType").Value.ToString();
                    CDXml.SelectSingleNode("//报关单表头信息/纳税单位").InnerText = rs.Fields.Item("U_PayTaxCompany").Value.ToString();
                    CDXml.SelectSingleNode("//报关单表头信息/境内目的地或境内货源地").InnerText = DeliverCode;
                    CDXml.SelectSingleNode("//报关单表头信息/合同协议号").InnerText = rs.Fields.Item("U_ContractNo").Value.ToString();
                    CDXml.SelectSingleNode("//报关单表头信息/备案号").InnerText = rs.Fields.Item("U_RecordNo").Value.ToString();
                    CDXml.SelectSingleNode("//报关单表头信息/批准文号").InnerText = rs.Fields.Item("U_JobOfferNo").Value.ToString();
                    CDXml.SelectSingleNode("//报关单表头信息/许可证编号").InnerText = rs.Fields.Item("U_LicenseNo").Value.ToString();
                    CDXml.SelectSingleNode("//报关单表头信息/运输工具名称").InnerText = rs.Fields.Item("U_Transportation").Value.ToString();
                    string MHWB = rs.Fields.Item("U_MainBill").Value.ToString();
                    MHWB = MHWB.Replace("-", "");
                    string SHWB = rs.Fields.Item("U_SplitBill").Value.ToString();
                    SHWB = SHWB.Replace("-", "");
                    CDXml.SelectSingleNode("//报关单表头信息/提单号").InnerText = MHWB + "_" + SHWB;
                    CDXml.SelectSingleNode("//报关单表头信息/包装种类").InnerText = rs.Fields.Item("U_PackageDescription").Value.ToString();
                    CDXml.SelectSingleNode("//报关单表头信息/运输方式").InnerText = rs.Fields.Item("U_ModeOfTransport").Value.ToString();
                    CDXml.SelectSingleNode("//报关单表头信息/成交方式").InnerText = rs.Fields.Item("U_BargainMethodCode").Value.ToString();
                    CDXml.SelectSingleNode("//报关单表头信息/贸易方式").InnerText = rs.Fields.Item("U_TradeMethod").Value.ToString();
                    CDXml.SelectSingleNode("//报关单表头信息/征免性质").InnerText = rs.Fields.Item("U_Property").Value.ToString();
                    CDXml.SelectSingleNode("//报关单表头信息/进出口类型").InnerText = Type;// rs.Fields.Item("").Value.ToString();
                    CDXml.SelectSingleNode("//报关单表头信息/件数").InnerText = ConvertNull(rs.Fields.Item("U_TotalNumber").Value.ToString());
                    CDXml.SelectSingleNode("//报关单表头信息/毛重").InnerText = ConvertNull(rs.Fields.Item("U_TotalWeight").Value.ToString());
                    CDXml.SelectSingleNode("//报关单表头信息/净重").InnerText = ConvertNull(rs.Fields.Item("U_TotalNetWeight").Value.ToString());
                    CDXml.SelectSingleNode("//报关单表头信息/运费标记").InnerText = rs.Fields.Item("U_FreightCharges").Value.ToString();
                    CDXml.SelectSingleNode("//报关单表头信息/运费或运率").InnerText = ConvertNull(rs.Fields.Item("U_FCRate").Value.ToString());
                    CDXml.SelectSingleNode("//报关单表头信息/运费币制").InnerText = rs.Fields.Item("FCCurrency").Value.ToString();

                    CDXml.SelectSingleNode("//报关单表头信息/保费标记").InnerText = rs.Fields.Item("U_SafeCharges").Value.ToString();
                    CDXml.SelectSingleNode("//报关单表头信息/保费或保率").InnerText = ConvertNull(rs.Fields.Item("U_SafeRate").Value.ToString());
                    CDXml.SelectSingleNode("//报关单表头信息/保费币制").InnerText = rs.Fields.Item("SafeCurrency").Value.ToString();

                    CDXml.SelectSingleNode("//报关单表头信息/杂费标记").InnerText = rs.Fields.Item("U_OtherCharges").Value.ToString();
                    CDXml.SelectSingleNode("//报关单表头信息/杂费或杂率").InnerText = ConvertNull(rs.Fields.Item("U_OtherRate").Value.ToString());
                    CDXml.SelectSingleNode("//报关单表头信息/杂费币制").InnerText = rs.Fields.Item("OtherCurrency").Value.ToString();

                    CDXml.SelectSingleNode("//报关单表头信息/收结汇方式或征税比例").InnerText = rs.Fields.Item("Collecting").Value.ToString();
                    CDXml.SelectSingleNode("//报关单表头信息/内销比率").InnerText = ConvertNull(rs.Fields.Item("U_DomesticRate").Value.ToString());
                    CDXml.SelectSingleNode("//报关单表头信息/进出口日期").InnerText = ConvertDatetime(rs.Fields.Item("U_ExImDate").Value);
                    CDXml.SelectSingleNode("//报关单表头信息/传输日期").InnerText = DateTime.Now.ToString("yyy-MM-dd"); //string.IsNullOrEmpty(rs.Fields.Item("U_SendDate").Value.ToString()) ? "" : Convert.ToDateTime(rs.Fields.Item("U_SendDate").Value.ToString()).ToString("yyyy-MM-dd");
                    CDXml.SelectSingleNode("//报关单表头信息/报关备注").InnerText = rs.Fields.Item("U_Remarks").Value.ToString();
                    CDXml.SelectSingleNode("//报关单表头信息/申报人标识").InnerText = rs.Fields.Item("U_CustomsBrokerFlag").Value.ToString();
                    CDXml.SelectSingleNode("//报关单表头信息/录入员IC卡号").InnerText = rs.Fields.Item("U_CustomsBrokerCDNo").Value.ToString();
                    CDXml.SelectSingleNode("//报关单表头信息/录入员姓名").InnerText = rs.Fields.Item("U_CustomsBroker").Value.ToString();

                }
                #endregion
                #region 报关单表体信息
                string customsDealarationLine = string.Empty;
                customsDealarationLine = CDXml.SelectSingleNode("//报关单表体信息").OuterXml;
                CDXml.SelectSingleNode("//报关单数据").RemoveChild(CDXml.SelectSingleNode("//报关单表体信息"));
                XmlDocument CDXmlLine = null;
                SQL = @"
                    SELECT 
                        Case When ISNULL(U_FirstUnit,'') = '' Then '' Else RIGHT(U_FirstUnit,len(U_FirstUnit)-1) End FirstUnit,
		                Case When ISNULL(U_SecondUnit,'') = '' Then '' Else RIGHT(U_SecondUnit,len(U_SecondUnit)-1) End SecondUnit,
                        Case When ISNULL(U_Unit,'') = '' Then '' Else RIGHT(U_Unit,len(U_Unit)-1) End ThirdUnit,
                        t1.Code CurrencyCode,
                        T0.*
                    FROM [@AVA_FF_{0}1] t0
                        LEFT JOIN DPA_empty..CurrencyType t1 on t0.U_Currency = t1.Symbol
                    Where T0.DocEntry = {1}";
                rs.DoQuery(string.Format(SQL, TableName, DocEntry));
                string Standard = string.Empty, DeclareValue = string.Empty;
                string[] Norms = null;
                for (int i = 0; i < rs.RecordCount; i++)
                {
                    CDXmlLine = new XmlDocument();
                    CDXmlLine.LoadXml(customsDealarationLine);
                    CDXmlLine.SelectSingleNode("//商品序号").InnerText = rs.Fields.Item("LineId").Value.ToString();
                    CDXmlLine.SelectSingleNode("//商品编码").InnerText = rs.Fields.Item("U_HSCode").Value.ToString();
                    CDXmlLine.SelectSingleNode("//货号").InnerText = rs.Fields.Item("U_ArticleNo").Value.ToString();
                    CDXmlLine.SelectSingleNode("//中文品名").InnerText = rs.Fields.Item("U_ProductName").Value.ToString();
                    CDXmlLine.SelectSingleNode("//英文品名").InnerText = rs.Fields.Item("U_ProducEName").Value.ToString();
                    Standard = rs.Fields.Item("U_Norms").Value.ToString();
                    Norms = Standard.Replace("；", ";").Replace("：", ":").Replace("||", "|").Split(new char[] { ';', ':', '|' }, System.StringSplitOptions.RemoveEmptyEntries);
                    DeclareValue = string.Empty;
                    for (int j = 0; j < Norms.Length; j++)
                    {
                        if (j % 2 == 0)
                            DeclareValue += Norms[j] + ":";
                        if (j % 2 == 1)
                            DeclareValue += Norms[j] + "|";

                    }
                    //DeclareValue = DeclareValue.Remove(0, 1);  //删除首项的"|"
                    DeclareValue = DeclareValue.Remove(DeclareValue.Length - 1, 1);  //删除末尾的"|"

                    CDXmlLine.SelectSingleNode("//规格型号").InnerText = DeclareValue;
                    CDXmlLine.SelectSingleNode("//备案序号").InnerText = rs.Fields.Item("U_RecordNo").Value.ToString();
                    CDXmlLine.SelectSingleNode("//成交数量").InnerText = ConvertNull(rs.Fields.Item("U_Quantity").Value.ToString());
                    CDXmlLine.SelectSingleNode("//成交单位").InnerText = rs.Fields.Item("ThirdUnit").Value.ToString();
                    CDXmlLine.SelectSingleNode("//单价").InnerText = ConvertNull(rs.Fields.Item("U_Price").Value.ToString());
                    CDXmlLine.SelectSingleNode("//总价").InnerText = ConvertNull(rs.Fields.Item("U_Total").Value.ToString());
                    CDXmlLine.SelectSingleNode("//币制").InnerText = rs.Fields.Item("CurrencyCode").Value.ToString();
                    CDXmlLine.SelectSingleNode("//第一法定数量").InnerText = ConvertNull(rs.Fields.Item("U_FirstQuantity").Value.ToString());
                    CDXmlLine.SelectSingleNode("//第一法定单位").InnerText = rs.Fields.Item("FirstUnit").Value.ToString();
                    CDXmlLine.SelectSingleNode("//第二法定数量").InnerText = ConvertNull(rs.Fields.Item("U_SecondQuantity").Value.ToString());
                    CDXmlLine.SelectSingleNode("//第二法定单位").InnerText = rs.Fields.Item("SecondUnit").Value.ToString();
                    CDXmlLine.SelectSingleNode("//原产地").InnerText = rs.Fields.Item("U_Origin").Value.ToString();
                    CDXmlLine.SelectSingleNode("//用途或生产厂家").InnerText = rs.Fields.Item("U_Manufacturer").Value.ToString();
                    CDXmlLine.SelectSingleNode("//征免方式").InnerText = rs.Fields.Item("U_ExemptionOfNature").Value.ToString();
                    CDXmlLine.SelectSingleNode("//工缴费").InnerText = ConvertNull(rs.Fields.Item("U_Charges").Value.ToString());
                    CDXmlLine.SelectSingleNode("//版本号").InnerText = rs.Fields.Item("U_Version").Value.ToString();
                    CDXmlLine.SelectSingleNode("//归类标志").InnerText = rs.Fields.Item("U_Flag").Value.ToString();
                    CDXmlLine.SelectSingleNode("//备注").InnerText = rs.Fields.Item("U_Remarks").Value.ToString();

                    //CDXmlLine.SelectSingleNode("//提单号").InnerText = rs.Fields.Item("U_WayBillNo").Value.ToString();
                    //CDXmlLine.SelectSingleNode("//进出境运输方式").InnerText = rs.Fields.Item("U_ModeOfTransport").Value.ToString();
                    //CDXmlLine.SelectSingleNode("//进出境运输工具编号").InnerText = rs.Fields.Item("U_TransportationNo").Value.ToString();
                    //CDXmlLine.SelectSingleNode("//进出境运输工具名称").InnerText = rs.Fields.Item("U_Transportation").Value.ToString();
                    //CDXmlLine.SelectSingleNode("//进出境运输工具航次").InnerText = rs.Fields.Item("U_Voyage").Value.ToString();
                    //CDXmlLine.SelectSingleNode("//实际进出境日期").InnerText = rs.Fields.Item("U_LeaveDate").Value.ToString();

                    XmlNode newnode = CDXml.SelectSingleNode("//报关单数据").OwnerDocument.ImportNode(CDXmlLine.LastChild, true);
                    CDXml.SelectSingleNode("//报关单数据").AppendChild(newnode);
                    rs.MoveNext();
                }
                string FreeTest = string.Empty;
                FreeTest = CDXml.SelectSingleNode("//报关单自由文本信息").OuterXml;
                CDXml.SelectSingleNode("//报关单数据").RemoveChild(CDXml.SelectSingleNode("//报关单自由文本信息"));
                CDXmlLine = new XmlDocument();
                CDXmlLine.LoadXml(FreeTest);
                XmlNode node = CDXml.SelectSingleNode("//报关单数据").OwnerDocument.ImportNode(CDXmlLine.LastChild, true);
                CDXml.SelectSingleNode("//报关单数据").AppendChild(node);
                #endregion
                string Platform = System.Configuration.ConfigurationManager.AppSettings["PlatformCode"];
                string Datetime = DateTime.Now.ToString("yyyyMMdd");
                string Number = DateTime.Now.ToString("HHmmssffff");// "0000000000".Substring(0, 10 - DocEntry.Length) + DocEntry.ToString();
                string TaskId = Platform + Datetime + Number;
                CDXml.SelectSingleNode("//企业配置信息/任务编号").InnerText = TaskId;
                CDXml.SelectSingleNode("//企业配置信息/企业编号").InnerText = TaskId;
                //保存                
                CDXml.Save(System.Configuration.ConfigurationManager.AppSettings["CustomsFilePath"] + @"\" + TaskId + ".xml");
                rs.DoQuery("UPDATE [@AVA_FF_O" + TableName + "] SET U_TaskNo='" + TaskId + "' Where DocEntry = " + DocEntry);
                return TaskId;
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
        private string ConvertNull(string Value)
        {
            if (Value == "0")
                return "";
            else
                return Value;
        }
        private string ConvertDatetime(DateTime Value)
        {
            if (Value.ToString("yyyy-MM-dd") == "1900-01-01")
                return "";
            else
                return Value.ToString("yyyy-MM-dd");
        }
    }
}
